package com.freesky.web.controller.biz.activity;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freesky.biz.activity.domain.TCouponBill;
import com.freesky.biz.activity.service.ICouponBillService;
import com.freesky.biz.activity.service.IRpaTaskService;
import com.freesky.biz.activity.service.IWebhookService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.constant.CommonConstants;
import com.freesky.common.core.controller.BaseController;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.utils.StringUtils;
import com.freesky.framework.web.service.SendAlarmService;
import com.opencsv.CSVReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStreamReader;
import java.util.*;

@RestController
@RequestMapping("/rpa/task")
public class RpaTaskController extends BaseController {

    @Autowired
    private IRpaTaskService rpaTaskService;

    @Autowired
    private IWebhookService webhookService;

    @Autowired
    private ICouponBillService couponBillService;

    @Autowired
    private SendAlarmService sendAlarmService;


    @Value("${oss.host}")
    private String host;

    private static final String WEB_HOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=23315a40-d096-4758-b766-c2cecc661e5d";

    //https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=23315a40-d096-4758-b766-c2cecc661e5d
    //http://127.0.0.1:8080/weixin/webhook/pushToWechat
    //https://pay.weixin.qq.com/index.php/core/info
    @PostMapping("/pushToWechat")
    public AjaxResult pushToWechat(@Validated @RequestBody String content) {
        System.out.println("content:"+content);
        String BASE64_IMAGE = "data:image/png;base64,";
        JSONObject jsonObject = JSON.parseObject(content);
        String mchId = jsonObject.getString("mchId");
        String base64 = jsonObject.getString("base64");

        webhookService.sendImage(WEB_HOOK_URL,base64);

        String msg = "";
        List<String> mobileList = new ArrayList<>();
        mobileList.add("18650992221");
        if("1615748766".equalsIgnoreCase(mchId)) {
            msg = "请用紫虫子账号进行扫码登陆,要注意账号不要出错!";
        } else if("1558805731".equalsIgnoreCase(mchId)){
            msg = "请用融易兑账号进行扫码登陆,要注意账号不要出错!";
        } else if("1682380270".equalsIgnoreCase(mchId)){
            msg = "请用标点网络账号进行扫码登陆,要注意账号不要出错!";
        }

        if(StringUtils.isNotEmpty(msg)) {
            webhookService.sendText(WEB_HOOK_URL, msg, mobileList);
        }

        return AjaxResult.success();
    }

    @GetMapping("/getUnProcessedCount")
    public AjaxResult getUnProcessedCount(String mchId) {
        Integer processCount = rpaTaskService.selectUnProcessedCount(mchId);
        return AjaxResult.success(processCount);
    }

    @GetMapping("/getRpaTaskList")
    public AjaxResult getTaskList(String mchId) {
        Integer nHours = Integer.parseInt(DateUtil.format(new Date(),"HH"));
        String intervalTime = "02:00:00";
        if(nHours>=19 && nHours<21){
            intervalTime = "01:30:00";
        } else if(nHours>=21 || nHours<=12){
            intervalTime = "01:00:00";
        }

        Integer processCount = rpaTaskService.selectCountProcessed(mchId,intervalTime);

        int nLeftCount = 50 - processCount.intValue();
        if(nLeftCount<=0){
            return AjaxResult.success(new ArrayList<>());
        } else {
            return AjaxResult.success(rpaTaskService.selectRpaTaskList(mchId,
                    Integer.valueOf(nLeftCount),intervalTime));
        }
    }

    @GetMapping("/rpaTaskProcessed")
    public AjaxResult rpaTaskProcessed(String stockId) {
        return AjaxResult.success(rpaTaskService.updateRpaTaskProcessed(stockId));
    }

    @PostMapping("/uploadCouponFile")
    public AjaxResult uploadCouponFile(MultipartFile file) throws Exception {
        String originalFileName = file.getOriginalFilename();
        try {
            originalFileName = FileUtil.getName(originalFileName).trim();
            System.out.println(originalFileName);
            String [] originalFileSplit = originalFileName.split("_");
            if(originalFileSplit.length<=3){
                return AjaxResult.error("文件名有误");
            }
            String stockId = originalFileSplit[0];
//            if(stockId.equalsIgnoreCase("16028589")
//                    || stockId.equalsIgnoreCase("16232547")){
//                return AjaxResult.success();
//            }

            String consumeStartTime = originalFileSplit[2];
            String consumeEndTime = originalFileSplit[3];
            if(StringUtils.isNotEmpty(consumeEndTime)){
                consumeEndTime = consumeEndTime.replaceAll(".csv","");
                int nIndex = consumeEndTime.indexOf("(");
                if(nIndex>0){
                    consumeEndTime = consumeEndTime .substring(0,nIndex);
                }
            }
            couponBillService.deleteBillByConsumeTime(stockId,consumeStartTime,consumeEndTime);

            List<TCouponBill> couponBills = new ArrayList<>();
            CSVReader reader = new CSVReader(new InputStreamReader(file.getInputStream(),"gbk"));
            String []record = null;
            long iLoop = 1;
            while ((record=reader.readNext())!=null) {
                if (iLoop == 1) {
                    iLoop = iLoop + 1;
                    continue;
                }
                String readStockId = record[0].trim();
                if(readStockId.equalsIgnoreCase("总条数")){
                    break;
                }

                System.out.println(record.toString());
                if (record.length < 11) {
                    logger.info(JSON.toJSONString(record));
                    continue;
                }

                //System.out.println(JSON.toJSONString(record));

                TCouponBill couponBill = new TCouponBill();
                couponBill.setId(SeqUtil.getSeqId());
                couponBill.setStockId(readStockId.replaceAll("`", ""));
                couponBill.setCouponId(record[1].trim().replaceAll("`", ""));
                couponBill.setType(record[2].trim().replaceAll("`", ""));
                couponBill.setAmt(Double.parseDouble(record[3].trim().replaceAll("`", "")));
                couponBill.setOrderMoney(Double.parseDouble(record[4].trim().replaceAll("`", "")));
                couponBill.setTradeType(record[5].trim().replaceAll("`", ""));
                couponBill.setTradeNo(record[6].trim().replaceAll("`", ""));
                couponBill.setConsumeTime(record[7].trim().replaceAll("`", ""));
                couponBill.setConsumeMchid(record[8].trim().replaceAll("`", ""));
                couponBill.setDeviceNo(record[9]);
                couponBill.setBankNo(record[10].trim().replaceAll("`",""));
                if (record.length > 11) {
                    couponBill.setCosumeCode1(record[11].trim().replaceAll("`", ""));
                }
                if (record.length > 12) {
                    couponBill.setConsumeCode2(record[12].trim().replaceAll("`", ""));
                }
                couponBills.add(couponBill);
                if(couponBills.size()> 10000){
                    couponBillService.addBatchOrUpdate(couponBills);
                    couponBills.clear();
                }
                iLoop = iLoop + 1;
            }

            if(couponBills.size()>0){
                //System.out.println(JSON.toJSONString(couponBills));
                couponBillService.addBatchOrUpdate(couponBills);
                couponBills.clear();
            }

            if(iLoop>2) {
                couponBillService.updateEmptyBankNo(stockId, consumeStartTime);
            }
            rpaTaskService.updateRpaTaskFinished(stockId,originalFileName,consumeStartTime);

            //System.out.println(JSON.toJSONString(couponBills));
            /*
            CsvReader csvReader = CsvUtil.getReader();
            List<TCouponBill> couponBills = csvReader.read(new String(file.getBytes(),"gbk"),TCouponBill.class);
            for(TCouponBill couponBill : couponBills){
                couponBill.setId(SeqUtil.getSeqId());
                String tradeNo = couponBill.getTradeNo();
                if(StringUtils.isNotEmpty(tradeNo)){
                    tradeNo = tradeNo.trim().replaceAll("`","");
                    couponBill.setTradeNo(tradeNo);
                }
                String bankNo = couponBill.getBankNo();
                if(StringUtils.isNotEmpty(bankNo)){
                    bankNo = bankNo.trim().replaceAll("`","");
                    couponBill.setBankNo(bankNo);
                }
            }
            System.out.println(JSON.toJSONString(couponBills));
            */

//            if(couponBills.size()>0) {
//                couponBillService.addBatchOrUpdate(couponBills);
//                couponBillService.updateEmptyBankNo(stockId, consumeStartTime);
//            }
//            rpaTaskService.updateRpaTaskFinished(stockId,originalFileName);

//            String key = "";
//            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//            Random rand = new Random();
//            String filePrefix = DateUtil.format(new Date(),"yyyyMM")+ File.separator + DateUtil.format(new Date(),"ddHHmmss") +"_"+String.valueOf(rand.nextInt(9999));
//
//            String fileKey = filePrefix + suffixName;
//            ossUtils.uploadFileStream(fileKey,file.getInputStream());
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("fileUrl", host + "/"+ fileKey);
//            ajax.put("originalFilename", file.getOriginalFilename());
            AjaxResult ajax = AjaxResult.success();
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            sendAlarmService.sendAlarmMail(CommonConstants.ALARM_EMAIL,"【异常】JOB-RPA文件处理-uploadCouponFile"+originalFileName,e.getMessage());
            return AjaxResult.error(e.getMessage());
        }

    }


}
